/**
 * 路由生成器
 * 将后端返回的路由数据转换为vue-router可用的路由数据
 * @param {*} asyncRoutes 后端返回的路由配置
 * @param {*} layout 布局组件，用于包裹路由组件
 * @returns 转换后的路由配置
 */

export function generateRoutes(asyncRoutes, layouts) {
    return asyncRoutes.map(route => {
        let component
        if (route.component) {
            if (route.component.startsWith('layouts/')) {
                component = layouts[route.component.split('layouts/')[1]]
            } else {
                component = () => import(`@/views/${route.component}.vue`)
            }
        }
        return {
            path: route.path,
            component,
            name: route.name || route.path.replace('/', ''),
            meta: {
                ...route.meta,
                cache: route.meta?.cache || false,
            },
            children: route.children ? generateRoutes(route.children, layouts) : [],
            redirect: route.redirect || undefined,
        }
    })
}
